package run.yiqi.blog.service;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import lombok.Getter;
import run.yiqi.blog.vo.EmailVo;

@Service
public class EmailService {
    public static final int TYPE_HTML = 0;
    public static final int TYPE_TXT = 1;
    
    @Value("${x.superuser.username}")
    private String superuserUsername;
    
    @Value("${x.mail.protocol}")
    private String mailProtocol;
    
    @Value("${x.mail.host}")
    private String mailHost;
    
    @Value("${x.mail.port}")
    private int mailPort;
    
    @Value("${x.mail.auth.username}")
    private String mailAuthUsername;
    
    @Value("${x.mail.auth.password}")
    private String mailAuthPassword;

    @Value("${x.mail.from}")
    private String mailFrom;

    @Getter
    @Value("${x.deploy.url}")
    private String deployUrl;
    
    @Value("${x.mail}")
    private boolean mail;
    
    /**
     * 发送邮件
     * @param emailVo
     * @throws EmailException
     */
    public void sendEmail(EmailVo emailVo) throws EmailException {
        if(mail) {
            HtmlEmail email = new HtmlEmail();
            
            email.setSubject(emailVo.getSubject());
            if(emailVo.getContentType() == TYPE_HTML) {
                email.setHtmlMsg(emailVo.getContent());
            } else {
                email.setTextMsg(emailVo.getContent());
            }
            if(emailVo.getTos().size()>0) {
                String[] tos = new String[emailVo.getTos().size()];
                emailVo.getTos().toArray(tos);
                email.addTo(tos);
            }
            if(emailVo.getCcs().size()>0) {
                String[] ccs = new String[emailVo.getCcs().size()];
                emailVo.getCcs().toArray(ccs);
                email.addCc(ccs);
            }
            
            email.setHostName(mailHost);
            email.setSmtpPort(mailPort);
            email.setDebug(true);
            email.setSSLOnConnect(true);
            email.setSslSmtpPort(String.valueOf(mailPort));
            email.setAuthentication(mailAuthUsername, mailAuthPassword);
            email.setFrom(mailFrom);
            email.setCharset("UTF-8");
            
            email.send();
        }
    }
}
